import React,{useEffect,useState} from 'react';
import axios from 'axios';
import { MonacoEditor } from './MonacoEditor';
import { EditorLanguages } from './MonacoEditor/editor';
interface IProps {
  link:string;
  type:string;
  name:string;
}

/** 文件预览 */
const CodeEditor = ({  link,type,name }: IProps) => {
  const [mdContent, setMdContent] = useState(''); // 保存Markdown文本内容
  const onTextChange = React.useCallback((value: string) => {
    setMdContent(value);
  }, []);
  const [language, setLanguage] = useState<EditorLanguages>('markdown');
  const getJsonText=(fileUrl: string): Promise<string> =>{
    return new Promise((ok, error) => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', fileUrl);
      xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          if (xhr.status === 200) {
            // 获取响应数据的原始文本内容
            const rawText = xhr.responseText;
            ok(rawText);
          } else {
            error('请求失败');
          }
        }
      };
      xhr.send();
    });
  }
  const initData = () => {
    switch (type) {
      case '.vue':
        setLanguage('vue');
        break;
      case '.tsx':
        setLanguage('tsx');
        break;
      case '.jsx':
        setLanguage('jsx');
        break;
      case '.js':
        setLanguage('javascript');
        break;
      case '.json':
        setLanguage('json');
        break;
      case '.html':
        setLanguage('html');
        break;
      case '.java':
        setLanguage('java');
        break;
      default:
        break;
    }
    if (link) {
      if (type === '.json') {
        getJsonText(link).then((data) => {
          setMdContent(data);
        });
        return;
      }
      axios.get(link).then((res) => {
        if (res.status === 200) {
          setMdContent(res.data);
          
        }
      });
    }
  };
  useEffect(() => {
    initData();
  }, []);

  return (
        <div className={'code'}>
          <div className="right">
            <div
              style={{
                marginBottom: '10px',
                marginLeft: '5px',
                position: 'fixed',
                top: '60px',
              }}>
              {name}
            </div>
            <MonacoEditor
              style={{width: '1000px', height: '1000px'}}
              value={mdContent}
              language={language}
              onChange={onTextChange}
            />
          </div>
        </div>
  );
};
export default CodeEditor;
